package com.next.aappublicapp.util;

import java.io.IOException;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.next.aap.client.RegisterDeviceResponse;
import com.next.aap.messages.TaskStatus;
import com.next.aappublicapp.server.service.DataServices;

public class GcmUtil {

	private static String GCM_SENDER_ID = "646798908058";
	private static String GCM_REGISTRATION_PREF = "GCM_REGISTRATION_PREF";
	private static GoogleCloudMessaging gcm;
	private static String regid;
	private static String PROPERTY_REG_ID = "PROPERTY_REG_ID";
	private static String PROPERTY_REG_ID_REGISTRATION_STATUS = "PROPERTY_REG_ID_REGISTRATION_STATUS";
	private static String REGISTRATION_STATUS_YES = "YES";
	
	public static String getGcmDeviceRegistrationId(Context context){
		SharedPreferences prefs = context.getSharedPreferences(GCM_REGISTRATION_PREF, Context.MODE_PRIVATE);
		regid = prefs.getString(PROPERTY_REG_ID, null);
		return regid;
	}
	public static void ensureDeviceIsRegistered(final Context context){
		// Make sure the app is registered with GCM and with the server
		SharedPreferences prefs = context.getSharedPreferences(GCM_REGISTRATION_PREF, Context.MODE_PRIVATE);
        
		String registrationStatus = prefs.getString(PROPERTY_REG_ID_REGISTRATION_STATUS, null);
		if(registrationStatus != null && REGISTRATION_STATUS_YES.equals(registrationStatus)){
			//Device RegId already registered with google and our server
			Log.i("Ravi", "Device RegId already registered with google and our server");
			return;
		}
		
		regid = prefs.getString(PROPERTY_REG_ID, null);

		Log.i("Ravi", "RegId is null so will register it now with google server ");
		gcm = GoogleCloudMessaging.getInstance(context);
        // If there is no registration ID, the app isn't registered.
        // Call registerBackground() to register it.
        if (regid == null) {
            registerBackground(context);
        }else{
        	new AsyncTask<Void, String, String>() {
    	        @Override
    	        protected String doInBackground(Void... params) {
    	            registerDeviceOnServer(context, regid);
    	            return "";
    	        }
    	        // Once registration is done, display the registration status
    	        // string in the Activity's UI.
    	        @Override
    	        protected void onPostExecute(String msg) {
    	        	CharSequence text = msg;
            		int duration = Toast.LENGTH_SHORT;
            		Toast toast = Toast.makeText(context, text, duration);
            		toast.show();	
    	            //mDisplay.append(msg + "\n");
    	        }
    			
    	    }.execute(null, null, null);
        	
        }
	}
	private static void registerBackground(final Context context) {
        new AsyncTask<Void, String, String>() {
	        @Override
	        protected String doInBackground(Void... params) {
	            String msg = "";
	            for(int i=0;i<3;i++){
	            	try {
		            	SharedPreferences prefs = context.getSharedPreferences(GCM_REGISTRATION_PREF, Context.MODE_PRIVATE);
		                regid = gcm.register(GCM_SENDER_ID);
		                msg = "Device registered, registration id=" + regid;
		                SharedPreferences.Editor editor = prefs.edit();
		                editor.putString(PROPERTY_REG_ID, regid);
		                editor.commit();
		                registerDeviceOnServer(context, regid);
		                break;
		            } catch (IOException ex) {
		            	Log.e("Ravi", "Error :" + ex.getMessage());
		            	ex.printStackTrace();
		                msg = "Error :" + ex.getMessage();
		                try {
							Thread.sleep(1000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
		            }
	            }
	            
	            return msg;
	        }
	        // Once registration is done, display the registration status
	        // string in the Activity's UI.
	        @Override
	        protected void onPostExecute(String msg) {
	        	/*
	        	CharSequence text = msg;
        		int duration = Toast.LENGTH_SHORT;
        		Toast toast = Toast.makeText(context, text, duration);
        		toast.show();
        		*/	
	            //mDisplay.append(msg + "\n");
	        }
			
	    }.execute(null, null, null);
	}
	
	private static void registerDeviceOnServer(Context context,String deviceRegId){
		try{
			Log.i("Ravi", "Calling DataService to register Device on Server");
        	RegisterDeviceResponse registerDeviceResponse =  DataServices.getInstance().registerDevice(regid);
        	if(registerDeviceResponse.getStatus() != null && (registerDeviceResponse.getStatus().equals(TaskStatus.STATUS_COMPLETED) ||registerDeviceResponse.getStatus().equals(TaskStatus.STATUS_ALREADY_REGISTERED))) {
        		deviceRegisteredSuccesfully(context, deviceRegId);
        	}
        }catch(Exception ex){
        	System.out.println("Exception occured while Registering device");
        	ex.printStackTrace();
        }
	}
	
	public static void deviceRegisteredSuccesfully(Context context,String deviceRegId){
		Log.i("Ravi", "deviceRegisteredSuccesfully = "+deviceRegId);
		SharedPreferences prefs = context.getSharedPreferences(GCM_REGISTRATION_PREF, Context.MODE_PRIVATE);
		String deviceRegIdOnDevice = prefs.getString(PROPERTY_REG_ID, "");
		if(deviceRegIdOnDevice.equals(deviceRegId)){
	        SharedPreferences.Editor editor = prefs.edit();
	        editor.putString(PROPERTY_REG_ID_REGISTRATION_STATUS, REGISTRATION_STATUS_YES);
	        editor.commit();
		}
	}

}
